package ru.mipt.sport.gui.model;

import java.util.List;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import ru.mipt.sport.model.interfaces.Institution;
import ru.mipt.sport.model.interfaces.Person;
import ru.mipt.sport.utils.DBUtils;

/**
 *
 * @author Anton Danshin <anton.danshin@frtk.ru>
 */
public class PeopleTableModel implements TableModel {

    private final DBUtils db;
    private List<Person> elements;
    
    public PeopleTableModel() {
        db = DBUtils.getInstance();
        refresh();
    }

    @Override
    public int getRowCount() {
        return elements.size();
    }

    @Override
    public int getColumnCount() {
        return 4;
    }

    @Override
    public String getColumnName(int columnIndex) {
        switch(columnIndex) {
            case 0 : return "ID";
            case 1 : return "Full Name";
            case 2 : return "Gender";
            case 3 : return "Institution";
        }
        return null;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch(columnIndex) {
            case 0 : return Long.class;
            case 1 : return String.class;
            case 2 : return String.class;
            case 3 : return Institution.class;
        }
        return null;
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        switch(columnIndex) {
            case 0 : return elements.get(rowIndex).getId();
            case 1 : return elements.get(rowIndex).getLastName() + " " + elements.get(rowIndex).getFirstName();
            case 2 : if(elements.get(rowIndex).getGender() == null) return "";
                     if(elements.get(rowIndex).getGender()) return "Male";
                     return "Female";
            case 3 : return elements.get(rowIndex).getCurrentInstitution();
        }
        return null;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        
    }

    @Override
    public void addTableModelListener(TableModelListener l) {
        
    }

    @Override
    public void removeTableModelListener(TableModelListener l) {
        
    }

    public Person getItemAt(int selectedRow) {
        return elements.get(selectedRow);
    }

    public final void refresh() {
        synchronized(db) {
            elements = db.getEntityManager().createQuery("select p from PersonEntity p order by p.lastName, p.firstName, p.middleName", Person.class).getResultList();
        }
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        db.close();
    }
    
    
    
}
